from Command import command, OperationDict
import Command

import requests
import sys
import json


#   TODO, define function

"""
1.@command params description:
    name: command parameter, If like "--add" or "-add",get the next string between "--name" as value or until the end
    value_type:int, str, float or None, if it's None, no input is required(input may not be valid)
    help:description of parameter function
2.How to use
    use OperationDict['name'].value get command-line's input
    if you get the input value, return the value of the specified type(default is str)
    if not any value return False(class 'bool')
    if you needn't any value return True(class 'bool')
3.Other issues
    The name of each command parameter must be the same as the function name, 
    These command parameters are the main parameters of the function
4.How to start
    Command.run()
"""


# If the format of the name is similar to "add",get the first string after "add" as value
# If like "--add" or "-add",get the next string between "--name" as value or until the end
@command(name="add", value_type=str, help="todo task description,insert a task,example todo add 'my task 1'")
@command(name="--s", value_type=str, help="this is a test")
def add():
    # use OperationDict[command_name_str].value get option value
    task_description = OperationDict["add"].value
    try:
        result = TODO().insert_task(task_description)
    except requests.exceptions.ConnectionError:
        print("Connection refused")
        return False
    if result.get("status") != "200":
        print(f'ErrorAdd:{error_code_to_text(result.get("status"))}')
        return False
    print(f"todo task:{task_description} add ok!")
    return True


@command(name="list", help="todo task description,insert a task,example todo add 'my task 1'")
@command(name="--state", value_type=str, help="[done/new]:view completed tasks or view the newly created task")
@command(name="--by", value_type=str, help="time[time ago]:view tasks before time,example --by 3 days ago")
@command(name="--created", value_type=str, help="time[time ago]:view tasks created by time ago")
def list():
    print(OperationDict['--state'].value)
    print(OperationDict['--by'].value)
    print(OperationDict['--created'].value)
    print(OperationDict['list'].value)


# 重构错误码翻译
def error_code_to_text(error_code):
    print("You may need help:", sys.argv[0] + ' help')
    error_codes = {
        "400": "请求无效",
        "403": "拒绝访问",
        "404": "找不到您想要的资源",
        "405": "资源被禁止",
        "500": "服务器错误",
        "1001": "time格式不正确",
        "1002": "id不正确或task已完成"
    }
    if error_codes.get(error_code, None):
        return error_codes[error_code]
    return "Error: Can't understand the command-line statement"


# c/s
class TODO:
    def __init__(self):
        self.url = "http://127.0.0.1:8888/todo/api/tasks"

    def update_url(self, url):
        self.url = url

    def update_port(self, port="3306"):
        self.url.replace(self.url.split(":")[2].split("/")[0], port)

    # 新增一个task,状态码为200
    def insert_task(self, task_description):
        headers = {'content-type': "application/json"}
        json_data = json.dumps({'description': task_description})
        res = requests.post(self.url, data=json_data, headers=headers)
        return json.loads(res.text)


if __name__ == '__main__':
    # 程序入口
    Command.run()